package cn.com.generaldata.os.service.impl.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.Constants;
import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.constant.ReportConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.paging.Event;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.paging.Result;
import cn.com.generaldata.os.pojo.Area;
import cn.com.generaldata.os.pojo.Role;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.util.MD5Util;

@Component
public class UnitServiceForWeb {

	private static Logger log = LoggerFactory.getLogger(UnitServiceForWeb.class);

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<Unit> unitDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<User> userDAO;
	private final static SimpleDateFormat sfd = new SimpleDateFormat("SSS");

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<Area> areaDAO;

	public String importUnits(File file) {
		Workbook wb = null;
		// int rowNum = 0;
		try {
			wb = new HSSFWorkbook(new FileInputStream(file));
			// wb = WorkbookFactory.create(file);
			// 生成一个字体
			Font font = wb.createFont();
			font.setColor(HSSFColor.RED.index);// HSSFColor.VIOLET.index //字体颜色
			Sheet sheet = wb.getSheetAt(0);
			if (sheet != null) {
				boolean error = false;
				String title = sheet.getRow(0).getCell(3).getStringCellValue();
				// 录入年份
				String unitYear = "";
				if ("企业信息录入模板".equals(title)) {
					String unitProper = "1";
					Cell cellYear = sheet.getRow(0).getCell(2);
					if (cellYear != null) {
						int cellType = cellYear.getCellType();
						if (cellType == 0) {
							DecimalFormat df = new DecimalFormat("0");
							double numericCellValue = cellYear.getNumericCellValue();
							unitYear = df.format(numericCellValue);
						} else if (cellType == 1) {
							unitYear = cellYear.getStringCellValue();
						}
					}
					// 企业性质
					String unitPro = sheet.getRow(1).getCell(2).getStringCellValue();
					if ("用海企业".equals(unitPro)) {
						unitProper = "2";
					} else if ("涉海企业".equals(unitPro)) {
						unitProper = "1";
					} else if ("开发区企业".equals(unitPro)) {
						unitProper = "3";
					}
					List<Unit> list = new ArrayList<Unit>();
					for (int i = 3; i <= sheet.getLastRowNum(); i++) {
						Unit unit = new Unit();
						// User user = new User();
						// user.setId(uid);
						// indicatorData.setCreatePre(user);
						org.apache.poi.ss.usermodel.Row row = sheet.getRow(i);
						// 企业名称
						Cell cellName = row.getCell(1);
						// 企业编号
						Cell cellNo = row.getCell(2);
						// 行政区划
						Cell cellArea = row.getCell(3);
						// 法定代表人
						Cell cellPer = row.getCell(4);
						// 通讯地址
						Cell cellAddress = row.getCell(5);
						// 邮政编码
						Cell cellMail = row.getCell(6);
						// 联系人姓名
						Cell cellContact = row.getCell(7);
						// 联系人电话
						Cell cellTel = row.getCell(8);
						Cell cellError = row.getCell(9);
						if (cellError == null) {
							cellError = row.createCell(9);
						}

						if (cellName != null) {
							CellStyle name = cellName.getCellStyle();

							unit.setUnitName(cellName.getStringCellValue());
						} else {
							error = true;
							cellError.setCellValue("请输入企业名称");
							CellStyle cellStyle = cellError.getCellStyle();
							cellStyle.setFont(font);
						}
						if (cellNo != null) {
							int cellType = cellNo.getCellType();

							if (cellType == 0) {
								DecimalFormat df = new DecimalFormat("0");
								double numericCellValue = cellNo.getNumericCellValue();
								unit.setSuperCompanyCode(df.format(numericCellValue));
							} else if (cellType == 1) {
								unit.setSuperCompanyCode(cellNo.getStringCellValue());
							}
						}
						if (cellArea != null) {
							CellStyle area = cellArea.getCellStyle();
							int cellType = cellArea.getCellType();
							String areaValue = "";
							if (cellType == 0) {
								DecimalFormat df = new DecimalFormat("0");
								double numericCellValue = cellArea.getNumericCellValue();
								areaValue = df.format(numericCellValue);
							} else if (cellType == 1) {
								areaValue = cellArea.getStringCellValue();
							}
							String hql = "from Area where areaName like :name or areaCode=:code";
							HashMap map = new HashMap();
							map.put("name", "%" + areaValue + "%");
							map.put("code", areaValue);
							Result hqlParam = areaDAO.hqlParam(hql, map, null);
							if (hqlParam.getOperationResult() != null && hqlParam.getOperationResult().size() > 0) {
								List<Area> operationResult = (List<Area>) hqlParam.getOperationResult();
								Area area2 = operationResult.get(0);
								unit.setArea(area2);
								unit.setRegistArea(area2);
							} else {
								// TODO Auto-generated catch block
								error = true;
								area.setFont(font);
								// cellYear.setCellStyle(value);
							}
						} else {
							error = true;
							cellError.setCellValue("指标行政区划不能为空");
							CellStyle cellStyle = cellError.getCellStyle();
							cellStyle.setFont(font);
						}
						if (cellPer != null) {
							unit.setFr(cellPer.getStringCellValue());
						}
						if (cellAddress != null) {
							unit.setAddr(cellAddress.getStringCellValue());
							unit.setRegistAdd(cellAddress.getStringCellValue());
						}
						if (cellMail != null) {
							int cellType = cellMail.getCellType();

							if (cellType == 0) {
								DecimalFormat df = new DecimalFormat("0");
								double numericCellValue = cellMail.getNumericCellValue();
								unit.setQyjt(df.format(numericCellValue));
							} else if (cellType == 1) {
								unit.setQyjt(cellMail.getStringCellValue());
							}
						}
						if (cellContact != null) {
							int cellType = cellContact.getCellType();
							if (cellType == 0) {
								DecimalFormat df = new DecimalFormat("0");
								double numericCellValue = cellContact.getNumericCellValue();
								unit.setProduct1(df.format(numericCellValue));
							} else if (cellType == 1) {
								unit.setProduct1(cellContact.getStringCellValue());
							}
						}
						if (cellTel != null) {
							int cellType = cellTel.getCellType();
							if (cellType == 0) {
								DecimalFormat df = new DecimalFormat("0");
								double numericCellValue = cellTel.getNumericCellValue();
								unit.setTel(df.format(numericCellValue));
							} else if (cellType == 1) {
								unit.setTel(cellTel.getStringCellValue());
							}
						}
						Role role = new Role();
						if ("涉海部门".equals(unitPro)) {
							role.setId("5");
						} else {
							role.setId("3");
						}
						unit.setRole(role);
						unit.setUnitProper(unitProper);
						unit.setCreateYear(unitYear);
						unit.setPractitioner(1);
						list.add(unit);
					}
					if (!error) {
						for (Unit data : list) {
							importUnit(data);
						}
						file.delete();
						return null;
					} else {
						FileOutputStream out = new FileOutputStream(file);
						wb.write(out);
						out.close();
						return file.getName();
					}

				} else {
					return "errorTitle";
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error("IO出错", e);
		}
		return "errorTitle";
	}

	public String importUnit(Unit unit) {
		// Boolean ret=true;
		if (unit == null || unit.getRole() == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("unit为空");
			return null;
		}
		boolean flag = false;
		if (unit.getSuperCompanyCode() != null && !"".equals(unit.getSuperCompanyCode())) {
			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "superCompanyCode", unit.getSuperCompanyCode()));
			List<Unit> units = unitDAO.find(Unit.class, filter, null);
			if (units != null && units.size() > 0) {
				flag = true;
				Unit unit2 = units.get(0);
				unit2.setArea(unit.getArea());
				unit2.setCreateYear(unit.getCreateYear());
				unit2.setSuperCompanyCode(unit.getSuperCompanyCode());
				unit2.setUnitName(unit.getUnitName());
				unit2.setAddr(unit.getAddr());
				unit2.setProduct1(unit.getProduct1());
				unit2.setFr(unit.getFr());
				unit2.setQyjt(unit.getQyjt());
				unit2.setTel(unit.getTel());
				unitDAO.saveOrUpdate(unit2);
				return unit2.getId();
			}
		}
		if (!flag) {
			if (unit.getId() == null || "".equals(unit.getId()))
				unit.setId(UUID.randomUUID().toString().replaceAll("-", ""));

			unitDAO.save(unit);
			User user = new User();
			user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			user.setUserLoginname(unit.getUnitName() + sfd.format(new Date()));
			user.setUserPasswd(MD5Util.getMD5ofStr("12345678"));
			user.setUserFlag("0");
			user.setEnterpriseUserUseSystem(1);
			user.setUserUnit(unit);
			user.setUserContactPhone(unit.getTel());
			user.setUserContactPerson(unit.getProduct1());
			user.setRole(unit.getRole());
			user.setArea(unit.getArea());
			user.setUserReportedDataType("2");
			user.setUserInstitutionCode(unit.getUnitInstitutionCode());
			user.setUserInstitutionName(unit.getUnitInstitutionName());
			user.setUserFaxTel(unit.getFax());
			user.setProduct1(unit.getProduct1());
			user.setProduct2(unit.getProduct2());
			user.setProduct3(unit.getProduct3());
			user.setPractitioner(unit.getPractitioner());
			user.setSuperCompanyCode(unit.getSuperCompanyCode());
			user.setLm(unit.getLm());
			user.setAddr(unit.getAddr());
			user.setRegistAdd(unit.getRegistAdd());
			user.setQh(unit.getQh());
			user.setZclx(unit.getZclx());
			user.setKgqk(unit.getKgqk());
			user.setYyzt(unit.getYyzt());
			user.setLsgx(unit.getLsgx());
			userDAO.save(user);
		}
		// webservice调用开始
		// ModelSend mo = new ModelSend();
		// mo.setObj(user);
		// mo.setFlag("4");
		// new Thread(mo).start();
		// webservice调用结束

		return unit.getId();
	}

	public String createUnit(Unit unit) {
		// Boolean ret=true;
		if (unit == null || unit.getRole() == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("unit为空");
			return null;
		}
		// 若是行政管理部门
		if (unit.getRole().getId().equals("4")) {
			// 判断该地区是否已经存在部门
			Unit existUnit = checkUnitArea(unit.getArea().getId(), null);
			if (existUnit != null) {
				// throw new
				// CommonException(ExceptionConstant.MSG_DUPLICATE_AREA_UNIT);
				log.error("existUnit不为空");
				return null;
			}
		}
		Unit checkUnitCode = checkUnitCode(unit.getSuperCompanyCode(), null);
		if (checkUnitCode != null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_DUPLICATE_AREA_UNIT);
			log.error("企业编号重复");
			return null;
		}
		Date date = new Date();
		unit.setCreateYear(String.valueOf(date.getYear()));
		if (unit.getId() == null || "".equals(unit.getId()))
			unit.setId(UUID.randomUUID().toString().replaceAll("-", ""));

		unitDAO.save(unit);
		// 别忘注了
		// User user=new User();
		// user.setUserLoginname(unit.getUnitName()+sfd.format(new Date()));
		// user.setUserPasswd(MD5Util.getMD5ofStr("12345678"));
		// user.setUserFlag("0");
		// user.setEnterpriseUserUseSystem(1);
		// user.setUserUnit(unit);
		// user.setUserContactPhone(unit.getTel());
		// user.setUserContactPerson(unit.getFr());
		// user.setRole(unit.getRole());
		// user.setArea(unit.getArea());
		// user.setUserReportedDataType("2");
		// user.setUserInstitutionCode(unit
		// .getUnitInstitutionCode());
		// user.setUserInstitutionName(unit
		// .getUnitInstitutionName());
		// user.setUserFaxTel(unit.getFax());
		// user.setProduct1(unit.getProduct1());
		// user.setProduct2(unit.getProduct2());
		// user.setProduct3(unit.getProduct3());
		// user.setPractitioner(unit.getPractitioner());
		// user.setSuperCompanyCode(unit
		// .getSuperCompanyCode());
		// user.setLm(unit.getLm());
		// user.setAddr(unit.getAddr());
		// user.setRegistAdd(unit.getRegistAdd());
		// user.setQh(unit.getQh());
		// user.setZclx(unit.getZclx());
		// user.setKgqk(unit.getKgqk());
		// user.setYyzt(unit.getYyzt());
		// user.setLsgx(unit.getLsgx());
		// userDAO.save(user);
		// webservice调用开始
		// ModelSend mo = new ModelSend();
		// mo.setObj(user);
		// mo.setFlag("4");
		// new Thread(mo).start();
		// webservice调用结束

		return unit.getId();
	}

	public Unit getUserUnit(String userId) {
		String hql = "from Unit un where exists(select id from User us where us.userUnit.id=un.id and us.id=:userId)";
		HashMap map = new HashMap();
		map.put("userId", userId);
		Result hqlParam = unitDAO.hqlParam(hql, map, null);
		if (hqlParam.getOperationResult() != null && hqlParam.getOperationResult().size() > 0) {
			List<Unit> operationResult = (List<Unit>) hqlParam.getOperationResult();
			return operationResult.get(0);
		}
		return null;
	}

	/**
	 * 批量删除单位
	 * 
	 * @param filter
	 * @return
	 */

	public void removeUnits(String[] ids) {
		if (ids == null || ids.length < 1) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			return;
		}

		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", ids));

		List<Unit> units = unitDAO.find(Unit.class, filter, null);
		if (units != null && units.size() > 0) {
			for (Unit unit : units) {
				Filter filter2 = new Filter();
				filter2.addRule(new FilterRule(FilterConstant.EQUAL, "userUnit.id", unit.getId()));
				List<User> users = userDAO.find(User.class, filter2, null);
				// Set<User> users = unit.getUsers();
				if (users != null && users.size() > 0) {
					for (User user : users) {
						user.setEnterpriseUserUseSystem(0);
						userDAO.update(user);
					}
				}
			}
		}
		unitDAO.delete(units);
	}

	/**
	 * 修改单位
	 * 
	 * @param filter
	 * @return
	 */

	public Unit modifyUnit(Unit unit) {
		// Boolean ret=true;
		if (unit == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("unit为空");
			return null;
		}
		// 若是行政管理部门
		if (unit.getRole().getId().equals("4")) {
			// 判断该地区是否已经存在部门
			Unit existUnit = checkUnitArea(unit.getArea().getId(), unit.getId());
			if (existUnit != null) {
				// throw new
				// CommonException(ExceptionConstant.MSG_DUPLICATE_AREA_UNIT);
				log.error("existUnit不为空");
				return null;
			}
		}
		Unit checkUnitCode = checkUnitCode(unit.getSuperCompanyCode(), unit.getId());
		if (checkUnitCode != null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_DUPLICATE_AREA_UNIT);
			log.error("企业编号重复");
			return null;
		}
		unitDAO.update(unit);
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "userUnit.id", unit.getId()));
		List<User> users = userDAO.find(User.class, filter, null);
		// Set<User> users = unit.getUsers();
		if (users != null && users.size() > 0) {
			for (User user : users) {
				user.setArea(unit.getArea());
				user.setRole(unit.getRole());
				user.setUserFlag("0");
				userDAO.update(user);
			}
		}
		// //webservice调用开始
		// ModelSend mo = new ModelSend();
		// mo.setObj(user);
		// mo.setFlag("3");
		// new Thread(mo).start();
		// webservice调用结束

		return unit;
	}

	/**
	 * 按ID查询单位
	 * 
	 * @param id
	 * @return
	 */

	public Unit queryUnitById(String id) {
		if (id != null) {
			Unit unit = unitDAO.get(Unit.class, id);
			return unit;
		}
		return null;
	}

	/**
	 * 分页查询单位
	 * 
	 * @param filter
	 * @return
	 */

	public Result queryUnits(Filter filter, Page page) {
		List<Unit> units = unitDAO.find(Unit.class, filter, page);
		int count = unitDAO.count(Unit.class, filter);

		if (page == null) {
			return new Result(1, 1, count, units, new ArrayList<Event>());
		}
		return new Result(page.getPageNumber(), page.getPageSize(), count, units, new ArrayList<Event>());
	}

	/**
	 * 分页查询单位
	 * 
	 * @param filter
	 * @return
	 */

	public Result queryUnitsByhql(String hql, HashMap map, Page page) {
		Result hqlParam = unitDAO.hqlParam(hql, map, page);

		return hqlParam;
	}

	/**
	 * 每个行政区划下只能有一个行政管理部门
	 * 
	 * @param areaId
	 * @return
	 */
	public Unit checkUnitArea(String areaId, String id) {
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", areaId));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "role.id", "4"));
		if (StringUtils.isNotBlank(id)) {
			filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "id", id.trim()));
		}

		List<Unit> units = unitDAO.find(Unit.class, filter, null);
		if (units.size() > 0) {
			return units.get(0);
		}
		return null;
	}

	/**
	 * 企业编号重复
	 * 
	 * @param areaId
	 * @return
	 */
	public Unit checkUnitCode(String code, String id) {
		if (StringUtils.isNotBlank(code)) {
			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "superCompanyCode", code));
			if (StringUtils.isNotBlank(id)) {
				filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "id", id.trim()));
			}

			List<Unit> units = unitDAO.find(Unit.class, filter, null);
			if (units.size() > 0) {
				return units.get(0);
			}
		}
		return null;
	}

	public Unit getProvinceOceanUnit() {
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", Constants.PROVINCE_AREA_ID));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "role.id", "4"));
		List<Unit> units = unitDAO.find(Unit.class, filter, null);
		if (units.size() > 0) {
			return units.get(0);
		}
		return null;
	}

	public cn.com.generaldata.os.vo.UnitVO toVo(Unit pUnit) {
		if (pUnit != null) {
			String roleId = pUnit.getRole() == null ? null : pUnit.getRole().getId();
			String roleName = pUnit.getRole() == null ? null : pUnit.getRole().getRoleName();
			// String industryId = pUnit.getIndustryId() == null ? null :
			// pUnit.getIndustry().getId();
			String industryName = null;
			String areaId = pUnit.getArea() == null ? null : pUnit.getArea().getId();
			String areaName = pUnit.getArea() == null ? null : pUnit.getArea().getAreaName();
			String lareaId = pUnit.getLarea() == null ? null : pUnit.getLarea().getId();
			String lareaName = pUnit.getLarea() == null ? null : pUnit.getLarea().getLareaName();
			String registAreaId = pUnit.getRegistArea() == null ? null : pUnit.getRegistArea().getId();
			String registAreaName = pUnit.getRegistArea() == null ? null : pUnit.getRegistArea().getAreaName();
			String registLAreaId = pUnit.getRegistLArea() == null ? null : pUnit.getRegistLArea().getId();
			String registLAreaName = pUnit.getRegistLArea() == null ? null : pUnit.getRegistLArea().getLareaName();
			List<String> users = new ArrayList<String>();
			if (pUnit.getUsers() != null) {
				for (User user : pUnit.getUsers()) {
					users.add(user.getId());
				}
			}
			String unitProperName = "";
			if (ReportConstant.YONGHAI_UNIT.equals(roleId)) {
				if (pUnit.getUnitProper() != null) {
					if (pUnit.getUnitProper().indexOf("1") != -1) {
						unitProperName += "涉海企业|";
						roleName = "涉海企业";
					}
					if (pUnit.getUnitProper().indexOf("2") != -1) {
						unitProperName += "用海企业|";
						roleName = "用海企业";
					}
					if (pUnit.getUnitProper().indexOf("3") != -1) {
						unitProperName += "开发区企业|";
						roleName = "开发区企业";
					}
				}
			}
			return new cn.com.generaldata.os.vo.UnitVO(pUnit.getId(), roleId, roleName, pUnit.getIndustryId(),
					industryName, areaId, areaName, lareaId, lareaName, pUnit.getUnitName(),
					pUnit.getUnitInstitutionName(), pUnit.getUnitInstitutionCode(), pUnit.getRegistAdd(),
					pUnit.getAddr(), registAreaId, registAreaName, registLAreaId, registLAreaName, pUnit.getQh(),
					pUnit.getTel(), pUnit.getFax(), pUnit.getMobile(), pUnit.getZclx(), pUnit.getLsgx(), pUnit.getDl(),
					pUnit.getZl(), pUnit.getXl(), pUnit.getLm(), pUnit.getYyzt(), pUnit.getProduct1(),
					pUnit.getProduct2(), pUnit.getProduct3(), pUnit.getKgqk(), pUnit.getPractitioner(),
					pUnit.getQyjt(), pUnit.getSuperCompanyCode(), pUnit.getFr(), pUnit.getUnitProper(), unitProperName,
					pUnit.getCreateYear(), users, pUnit.getProInfo(), pUnit.getKkx(), pUnit.getKky(), pUnit.getKkz(),
					pUnit.getDlx(), pUnit.getDly(), pUnit.getDlz(), pUnit.getPid());
		}
		return null;
	}
}
